import AppConfig from "../config/AppConfig";

export default class Utils {

    /**
    * 计算缩放
    * @param base 基础值
    * @param max 最大值
    * @param arr 缩放列表
    * @returns 
    */
    static lerpScale(base: number, max: number, ...arr: number[]) {
        for (let elm of arr) {
            base = base * elm / max;
        }
        return Math.min(max, base);
    }

    /**
     * 数学sin cos ...
     */
    private static mathSinCos(attr, angle: number): number {
        return Math[attr](angle * Math.PI / 180);
    }

    /**
     * sin
     * @param angle 角度，0~360
     */
    public static sin(angle: number): number {
        return this.mathSinCos('sin', angle);
    }

    /**
     * cos
     * @param angle 角度，0~360
     */
    public static cos(angle: number): number {
        return angle % 180 == 90 ? 0 : this.mathSinCos('cos', angle);
    }



    public static random() {
        return Math.random();
    }

    public static randomInt(min: number, max: number) {
        return Math.floor(this.random() * (max - min)) + min
    }

    public static randomFlot(min: number, max: number) {
        return this.random() * (max - min) + min;
    }


    /**
    * 取数组的随机值
    * @param array 数组
    * @param item 子项，存在时则随机出来的值不为item的值，若长度小于等于1，则无效
    */
    static randomInArray<T>(array: T[], item?: T | ((o: T) => boolean)): T {
        let len = array.length, splice = len;
        if (len > 1 && !Utils.isNil(item)) {

            let index = typeof item === "function" ? array.findIndex(<any>item) : array.indexOf(item);

            if (index > -1) {
                len--;
                splice = index;
            }
        }

        let rndIdx = this.randomInt(0, len);
        if (rndIdx >= splice) {
            ++rndIdx;
        }

        return array[rndIdx];
    }


    static getPrice(price: number) {
        if (AppConfig.TW) {
            return `$ ${price}`
        }

        return `￥ ${price}`;
    }

    static isUndefined(o) {
        return typeof o === "undefined";
    }

    static isNil(o) {
        return Utils.isUndefined(o) || o === null;
    }


    static parseNum(str: string) {
        let num = Number(str);
        if (isNaN(num)) return 0;

        return num;
    }

}